package network.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoServer {
    private ServerSocket serverSocket;

    public EchoServer(int port) throws IOException{ 
        //服务器启动，就会绑定到port端口上面
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException{
        System.out.println("服务器启动");

        ExecutorService threadPool = Executors.newCachedThreadPool();
        while (true) {
            Socket socket = serverSocket.accept();
            //多线程版本
//            Thread t = new Thread(()->{
//                //这个地方this和socket都是lambda从外层作用域中捕获的变量
//                this.processConnection(socket);
//            });
//            t.start();

            //线程池版本
            threadPool.submit(()->{
                processConnection(socket);
            });
        }
    }

    private void processConnection(Socket socket) {
        System.out.printf("[%s:%d]客户端上线\n",socket.getInetAddress().toString(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //实现通信的代码
            //一个客户端可能会和服务器有多轮的请求响应交互
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                //1.读取请求并解析 这里有更简单的方法
                if (!scanner.hasNext()) {
                    //针对客户端下线逻辑的处理，比如客户端断开连接了
                    //如果使用read，就会返回负一的情况
                    System.out.printf("[%s:%d]客户端下线\n",socket.getInetAddress().toString(),socket.getPort());
                    break;
                }
                // System.out.println("服务器收到数据了!");
                String request = scanner.next();
                //2.根据请求计算解析
                String response = process(request);
                //3.把响应写回到客户端
                writer.println(response);
                writer.flush();
                System.out.printf("[%s:%d]req:%s resp:%s\n",socket.getInetAddress().toString(),socket.getPort(),request,response);
            }
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer server = new EchoServer(9090);
        server.start();
    }
}
